#include "Bullet.h"
#include "StaticData.h"
USING_NS_CC;

Bullet::Bullet():_bulletSprite(0)
{
}

Bullet::~Bullet()
{
}

bool Bullet::init()
{
	_bulletSprite=CCSprite::createWithSpriteFrameName(StaticData::getInstance()->stringFromKey("bullet"));
	_bulletSprite->setAnchorPoint(CCPoint(0.5,1.0));
	addChild(_bulletSprite);
	return true;
}

Bullet* Bullet::create()
{
	Bullet* pRet=new Bullet;
	if(pRet&&pRet->init())
	{
		pRet->autorelease();
		return pRet;
	}
	else
	{
		delete pRet;
		pRet=0;
		return 0;
	}
}

void Bullet::flyTo(CCPoint target)
{
	CCPoint startInNodeSpace = CCPointZero;
	CCPoint startInWorldSpace=getParent()->convertToWorldSpace(startInNodeSpace);
	CCPoint targetInNodeSpace=getParent()->convertToNodeSpace(target);
	float angle=ccpAngleSigned(ccpSub(target,startInWorldSpace),CCPoint(0,1));
	setRotation(CC_RADIANS_TO_DEGREES(angle));
	setPosition(startInNodeSpace);
	setVisible(true);

	float speed=300;
	float duration=ccpDistance(startInNodeSpace,targetInNodeSpace)/speed;
	CCMoveTo* moveTo=CCMoveTo::create(duration,targetInNodeSpace);
	CCCallFunc* callFunc=CCCallFunc::create(this,callfunc_selector(Bullet::end));

	CCFiniteTimeAction* seq=CCSequence::create(moveTo,callFunc,0);
	seq->setTag(0);
	runAction(seq);
}

void Bullet::end()
{
	stopActionByTag(0);
	setVisible(false);
}

CCPoint Bullet::getCollisionPoint()
{
	return getParent()->convertToWorldSpace(getPosition());
}
